package com.heima.big_event03.controller;

import com.heima.big_event03.entity.User;
import com.heima.big_event03.service.UserService;
import com.heima.big_event03.utils.JwtUtil;
import com.heima.big_event03.utils.Result;
import com.heima.big_event03.utils.ThreadLocalUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.URL;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.Pattern;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户表(User)表控制层
 *
 * @author makejava
 * @since 2025-03-04 20:44:40
 */
@RestController
@RequestMapping("/user")
@Api("用户信息")
@Validated//<-------------使用注解校验前的细节
@Slf4j
public class UserController {
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;

    /**
     * 注册
     */
    @PostMapping("/register")
    @ApiOperation("注册")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$") String password){
        //校验用户名和密码是否规范
        //校验用户名是否已经存在
        User u = this.userService.queryByUserName(username);
        if(u != null){
            return Result.error("该用户已存在!!!");
        }
        //注册
        this.userService.register(username,password);
        return Result.success();
    }

    /**
     * 登录
     */
    @PostMapping("/login")
    @ApiOperation("登录")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$") String password){
        //校验用户名是否存在
        User u = this.userService.queryByUserName(username);
        if(u == null){
            return Result.error("用户名不存在，请先注册！！");
        }
        //校验密码是否正确
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if(!u.getPassword().equals(password)){
            return Result.error("密码有误!!");
        }

        //把ID存储到ThreadLocal中
//        ThreadLocalUtil.set(u.getId());

        //生成jwt返回前端
        Map<String, Object> cliams = new HashMap<>();
        cliams.put("id",u.getId());
        cliams.put("username",username);
        String token = JwtUtil.getToken(cliams);
        return Result.success(token);
    }

    /**
     * 获取用户详细信息
     */
    @GetMapping("/userInfo")
    @ApiOperation("获取用户详细信息")
    public Result<User> userInfo(){
        Map<String, Object> claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        User u = this.userService.queryByUserName(username);
        return Result.success(u);
    }

    /**
     * 修改用户信息
     */
    @PutMapping("/update")
    @ApiOperation("修改用户信息")
    public Result updateInfo(@RequestBody User user){
        this.userService.update(user);
        return Result.success();
    }


    /**
     * 更新用户头像
     */
    @PatchMapping("/updateAvatar")
    @ApiOperation("更新用户头像")
    public Result updateAvatar(@URL String avatarUrl){
        this.userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    /**
     * 更新用户密码
     * @return
     */
    @PatchMapping("/updatePwd")
    @ApiOperation("更新用户密码")
    public Result updataPwd(@RequestBody Map<String, String> params){
        String old_pwd =params.get("old_pwd");
        String new_pwd =params.get("new_pwd");
        String re_pwd = params.get("re_pwd");
        if(!StringUtils.hasLength(old_pwd) ||!StringUtils.hasLength(new_pwd) ||!StringUtils.hasLength(re_pwd)){
            return Result.error("缺少必要的参数");
        }

        //加密处理
        old_pwd = DigestUtils.md5DigestAsHex(old_pwd.getBytes());
        new_pwd = DigestUtils.md5DigestAsHex(new_pwd.getBytes());
        re_pwd = DigestUtils.md5DigestAsHex(re_pwd.getBytes());

        //校验old_pwd与原密码是否一致
        Map<String, Object> claims = ThreadLocalUtil.get();
        String id = (String) claims.get("id");
        User u = this.userService.queryById(id);
//        log.info("开始更新用户密码{}",u.getPassword());
        if(!u.getPassword().equals(old_pwd)){
            return Result.error("原密码有误");
        }
        //校验new_pwd与re_pwd是否一致
        if(!new_pwd.equals(re_pwd)){
            return Result.error("两次密码不一致");
        }
        //更新密码
        u.setId(id);
        u.setPassword(new_pwd);
        u.setUpdateTime(LocalDateTime.now());
        this.userService.updatePwd(u);
        return Result.success();
    }

}

